import { diskStorage } from 'multer';
import { extname } from 'path';
import { HttpException, HttpStatus } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';

// 生成唯一文件名（更简洁的方式）
const generateUniqueFilename = (req, file, callback) => {
  const uniqueName = uuidv4();
  callback(null, `${uniqueName}${extname(file.originalname)}`);
};

// 音频文件类型验证
const audioFileFilter = (req, file, callback) => {
  // 允许的音频文件类型
  const allowedMimeTypes = [
    'audio/mpeg',
    'audio/wav',
    'audio/ogg',
    'audio/aac',
    'audio/flac',
    'audio/mp3',
  ];

  if (allowedMimeTypes.includes(file.mimetype)) {
    callback(null, true);
  } else {
    callback(
      new HttpException(
        '不支持的文件类型。仅支持MP3、WAV、OGG、AAC、FLAC等音频格式。',
        HttpStatus.BAD_REQUEST,
      ),
      false,
    );
  }
};

// 图片文件类型验证
const imageFileFilter = (req, file, callback) => {
  // 允许的图片文件类型
  const allowedMimeTypes = [
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/gif',
    'image/webp',
  ];

  if (allowedMimeTypes.includes(file.mimetype)) {
    callback(null, true);
  } else {
    callback(
      new HttpException(
        '不支持的图片格式。仅支持JPG、PNG、GIF、WebP格式。',
        HttpStatus.BAD_REQUEST,
      ),
      false,
    );
  }
};

// 音频上传配置
export const audioMulterConfig = {
  storage: diskStorage({
    destination: './uploads', // 文件保存目录
    filename: generateUniqueFilename,
  }),
  limits: {
    fileSize: 50 * 1024 * 1024, // 限制文件大小为50MB
  },
  fileFilter: audioFileFilter,
};

// 图片上传配置
export const imageMulterConfig = {
  storage: diskStorage({
    destination: './uploads/avatars', // 图片保存目录
    filename: generateUniqueFilename,
  }),
  limits: {
    fileSize: 2 * 1024 * 1024, // 限制文件大小为2MB
  },
  fileFilter: imageFileFilter,
};

// 文件上传配置类（用于依赖注入）
export class MulterConfig {}
